﻿using Growatt.WaveData.Coff;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace Growatt.WaveData.DataSetResolve
{
    public class InitialData
    {

        /// <summary>
        /// .out文件或者是elf文件
        /// </summary>
        public string CoffPath { get; }
        CreatVariableAddress creatVariableAddress = null;
        public InitialData(string outelfPath, List<string> ParaName)
        {
            ListParamAdd.Clear();
            File.Delete(temPathofd6xFile);
            this.CoffPath = outelfPath;
            if (File.Exists(outelfPath))
            {
                if (outelfPath.EndsWith(".out"))
                    InitialCoff(outelfPath);
                creatVariableAddress = new CreatVariableAddress(outelfPath, this);
                var re = creatVariableAddress.CalculateAddressList(ParaName);
          
                ListParamAdd.AddRange(re);
            }
        }

        public  List<string> ListParamAdd = new List<string>();
        List<SymbolModel> symbolModels = new List<SymbolModel>();
        Dictionary<string, List<CoffSymbolModel>> keyValuePairs = new Dictionary<string, List<CoffSymbolModel>>();
        public List<CoffSymbolModel> Total_coffSymbolModels = new List<CoffSymbolModel>();
        string temPathofd6xFile = $"{System.Environment.CurrentDirectory}\\Parser\\example.txt";
        public void InitialCoff(string f)
        {
            try
            {
                var appOutpath = Path.Combine(Environment.CurrentDirectory, "Parser", "App.out");
                if (File.Exists(appOutpath))
                {
                    string content = $"ParseELF.exe -arg3 App.out";
                    string batPath = $"{System.Environment.CurrentDirectory}\\Parser\\Temp.bat";
                    creatFunc(content, batPath);
                    if (!File.Exists(temPathofd6xFile))
                    {
                        MessageBox.Show("文件不存在");
                        return;
                    }
                    var datas = LoadFilelistString(temPathofd6xFile).ToList();
                    var le = datas.Count;
                    for (global::System.Int32 i = 0; i < le; i++)
                    {
                        var item = datas[i];
                        var groups = Regex.Matches(item, "(?<=\\[)(.+?)(?=\\])");
                        if (groups != null && groups[0].ToString() != null && !keyValuePairs.ContainsKey(groups[0].ToString()))
                        {
                            keyValuePairs.Add(groups[0].ToString(), new List<CoffSymbolModel>());
                        }
                        if (groups.Count == 8)
                        {
                            CoffSymbolModel coffSymbolModel = new CoffSymbolModel(groups[1].ToString(), groups[2].ToString(), groups[3].ToString(), groups[4].ToString(), groups[5].ToString(), groups[6].ToString(), groups[7].ToString());
                            keyValuePairs[groups[0].ToString()].Add(coffSymbolModel);
                            Total_coffSymbolModels.Add(coffSymbolModel); //总的所有变量


                        }

                    }
                    //string st = ObjectToJson(Total_coffSymbolModels);
                    //Console.WriteLine(st);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                MessageBox.Show("生成文件失败!");
            }

        }
        public void ChangeVariable(string address,string  Paraname, string  paraValue , string Paratype)
        {
            try
            {
                var appOutpath = Path.Combine(Environment.CurrentDirectory, "App.out");
                if (File.Exists(appOutpath))
                {
                    string content = $"ParseELF.exe -cf App.out -ca {address} -cv {paraValue} -ct {Paratype} -cn {Paraname}";
                    string batPath = $"{System.Environment.CurrentDirectory}\\Parser\\Temp.bat";
                    creatFunc(content, batPath);
                    if (!File.Exists(temPathofd6xFile))
                    {
                        MessageBox.Show("文件不存在");
                        return;
                    }
                    var datas = LoadFilelistString(temPathofd6xFile).ToList();
                    var le = datas.Count;
                    for (global::System.Int32 i = 0; i < le; i++)
                    {
                        var item = datas[i];
                        var groups = Regex.Matches(item, "(?<=\\[)(.+?)(?=\\])");
                        if (groups != null && groups[0].ToString() != null && !keyValuePairs.ContainsKey(groups[0].ToString()))
                        {
                            keyValuePairs.Add(groups[0].ToString(), new List<CoffSymbolModel>());
                        }
                        if (groups.Count == 8)
                        {
                            CoffSymbolModel coffSymbolModel = new CoffSymbolModel(groups[1].ToString(), groups[2].ToString(), groups[3].ToString(), groups[4].ToString(), groups[5].ToString(), groups[6].ToString(), groups[7].ToString());
                            keyValuePairs[groups[0].ToString()].Add(coffSymbolModel);
                            Total_coffSymbolModels.Add(coffSymbolModel); //总的所有变量


                        }

                    }
                    //string st = ObjectToJson(Total_coffSymbolModels);
                    //Console.WriteLine(st);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                MessageBox.Show("生成文件失败!");
            }

        }

        public List<string> LoadFilelistString(string FileToRead)
        {
            List<string> line = new List<string>();
            using (StreamReader st = new StreamReader(FileToRead))
            {
                //逐行读取文件处理至文件结束
                string str = String.Empty;
                while ((str = st.ReadLine()) != null)
                {
                    line.Add(str);
                }
            }
            return line;
        }
        public bool WriteBatFile(string filePath, string fileContent)
        {
            try
            {
                if (File.Exists(filePath))
                    File.Delete(filePath);
                FileStream fs1 = new FileStream(filePath, FileMode.Create, FileAccess.Write);//创建写入文件
                StreamWriter sw = new StreamWriter(fs1, Encoding.GetEncoding("GB2312"));
                sw.WriteLine(fileContent);//开始写入值
                sw.Close();
                fs1.Close();
                return true;
            }
            catch (Exception ex)
            {
                //DuiHelperLog.WriteErrorLog(ex);
                return false;
            }
        }
        public void creatFunc(string str, string batPath, bool fal = false)
        {

            StringBuilder stringBuilder = new StringBuilder();
            {
                //stringBuilder.AppendLine($"hexview /s {typeName} /cs9:@{textBox_add.Text};{textBox_rangeFirst.Text}-{textBox_RangeSec.Text} /XI -o {typeoutName}");
                stringBuilder.AppendLine(str);
                var writeResult = WriteBatFile(batPath, stringBuilder.ToString());//如果存在则清空
                if (writeResult)
                {
                    var proc = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = batPath,
                            WorkingDirectory = $"{System.Environment.CurrentDirectory}\\Parser", //当前.bat工作目录
                            UseShellExecute = false,
                            CreateNoWindow = true,

                        }
                    };
                    proc.StartInfo.Verb = "runas";
                    proc.StartInfo.RedirectStandardInput = true;
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.RedirectStandardError = true;
                    proc.Start();
                    while (!proc.StandardOutput.EndOfStream)
                    {
                        string line = proc.StandardOutput.ReadLine();
                       // Debug.WriteLine(line);

                    }

                    while (!proc.StandardError.EndOfStream)
                    {
                        string line = proc.StandardError.ReadLine();
                        //Debug.WriteLine(line);
                    }

                    proc.WaitForExit();
                    proc.Close();

                }
            }

        }
    }
}